<template>
  <Dialogdrawerdefect
    :ddtvisible="bindDialogVisible"
    size="360px"
    direction="rtl"
    :has-modal="false"
    :modal="false"
    @close="handleClose"
    :title="`HIS绑定【${bindInfo.bigpart}】`">
    <div class="cont_box" style="padding-top: 0px !important;" v-loading="saveLoading">
      <!-- <AppInfoTitle>
        <b class="fs-16">{{`HIS绑定【${bindInfo.bigpart}】`}}</b>
      </AppInfoTitle> -->
      <section class="dialog-con">
        <section class="right-tree">
          <tree
            :data="checkroomList"
            show-checkbox
            default-expand-all
            node-key="label"
            ref="checkroomTree"
            @check="handleCheckCheckroom"
            :filter-node-method="filterNode"
            :props="defaultProps">
          </tree>
        </section>
      </section>
      <div class="buttons flex flex-row justify-between">
        <el-button size="small" @click="handleClose">关 闭</el-button>
        <el-button type="primary" size="small" @click="handleSave">保 存</el-button>
      </div>
    </div>
  </Dialogdrawerdefect>
</template>
<script>
import { getCheckRoomList, getHisCheckroomList, hisBindCheckroom } from '@/api/api.js'
import Dialogdrawerdefect from '@/components/dialogbox/dialogDrawerDefect'
// import AppInfoTitle from '@/components/appInfoTitle/index'
import Tree from '@/assets/js/tree/index.js'

export default {
  name: 'BindCheckroom',
  components: {
    Dialogdrawerdefect,
    Tree
    // AppInfoTitle
  },
  props: {
    bindDialogVisible: {
      type: Boolean,
      default: false
    },
    bindInfo: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      checkType: [],
      filterText: '',
      filterIds: [],
      saveLoading: false,
      ruleForm: {
        id: '',
        examNotice: '',
        workCount: '',
        filter: ''
      },
      smallPart: [],
      checkroomList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      bindData: [], // 绑定数据需要传  {smallpart:'', checkRoom:[]}
      curPart: ''// 当前选中的part
    }
  },
  watch: {
    checkType(val) {
      this.filterIds = []
      this.filterTree('tree', val, this.filterText)
    },
    filterText(val) {
      this.filterTree('tree', this.checkType, val)
    },
    bindInfo: {
      handler(val) {
        if (val.hospitalCode && val.id) {
          this.bindData = []
          this.checkroomList = []
          this.init()
        }
      },
      deep: true
    },
    checkTypeSelectFilter() {
      this.filterTree('tree', this.checkType, this.filterText)
    }
  },
  methods: {
    filterTree($el, val1, val2) {
      this.$refs[`${$el}`] && this.$refs[`${$el}`].filter(val1)
      this.$refs[`${$el}`] && this.$refs[`${$el}`].filter(val2)
    },
    init() {
      let data = {
        hospitalCode: this.bindInfo.hospitalCode,
        dep: this.bindInfo.dep
      }
      this.smallPart = this.bindInfo.smallpart.split(',').map(item => { return { 'label': item } })

      this.curPart = this.smallPart[0].label
      let checkroomData = {
        hospitalCode: this.bindInfo.hospitalCode,
        Bigpart: this.bindInfo.bigpart,
        Smallpart: this.smallPart[0] ? this.smallPart[0].label : ''
      }
      Promise.all([getCheckRoomList(data), getHisCheckroomList(checkroomData)]).then((val) => {
        console.log('Promise.all=>val', val)
        if (val[0] && val[0].code === 10000) {
          this.checkroomList = val[0].content.list.map(item => {
            return {
              label: item,
              id: item,
              text: item
            }
          })
          console.log('this.checkroomList', this.checkroomList)
        }
        if (val[1] && val[1].code === 10000) {
          let checked = val[1].content.list.map(item => { return { 'label': item.checkRoom } })
          this.$nextTick(() => {
            this.$refs.checkroomTree && this.$refs.checkroomTree.setCheckedNodes(checked)
            // this.$refs.smallTree.setCurrentKey(this.smallPart[0])
          })
        }
      })
    },
    handleChangePart(nodeData, checkedData) {
      this.curPart = nodeData.label

      let checkroomData = {
        hospitalCode: this.bindInfo.hospitalCode,
        Bigpart: this.bindInfo.bigpart,
        Smallpart: nodeData.label
      }
      getHisCheckroomList(checkroomData).then(res => {
        if (res && res.code === 10000) {
          let checked = res.content.list.map(item => { return { 'label': item.checkRoom } })
          this.$nextTick(() => {
            this.$refs.checkroomTree.setCheckedNodes(checked)
          })
        }
      })
    },
    handleClose() {
      this.$emit('myClose')
    },
    handleCheckCheckroom(nodeData, checkedData) {
      if (!this.curPart) {
        this.$message.warning('请选择检查项目')
        return
      }
      let existedPart = false
      // 从绑定数据中查找， 如果存在，修改； 如果不存在，push
      for (let i = 0; i < this.bindData.length; i++) {
        if (this.curPart === this.bindData[i].smallpart) {
          existedPart = true
          this.bindData[i].checkRoom = checkedData.checkedKeys
          break
        }
      }
      if (!existedPart) {
        this.bindData.push({
          smallpart: this.curPart, checkRoom: checkedData.checkedKeys
        })
      }
    },
    handleSave() {
      for (let i = 0; i < this.bindData.length; i++) {
        let tempData = this.bindData[i]
        tempData.hospitalCode = this.bindInfo.hospitalCode
        tempData.bigpart = this.bindInfo.bigpart

        hisBindCheckroom(tempData).then(res => {
          if (res && res.code === 10000) {
            this.$message.success('成功绑定数据')
            this.handleClose()
          }
        })
      }
    },
    filterNode(value, data, node) {
      console.log('filterNode=>value, data, node', value, data, node)
      let result = this.filterNodeComm('filterIds', 'checkTypeSelectFilter', value, data, node)
      // console.log('filterNode_result', result)
      return result
    },
    // 检查类型过滤，公用函数
    filterNodeComm(idsKey, stFilter, value, data, node) {
      console.log('filterNodeComm=>data', data)
      if ((this[`${idsKey}`].length == 0 && !value) || (typeof value === 'object' && value.length === 0)) {
        console.log('进入这里')
        node = {}
        node ? node.expanded = false : null
        return true
      }
      if (typeof value === 'string') {
        let flag = false
        // 判断文字查询是否指定字段
        if (this[`${stFilter}`] && this[`${stFilter}`] * 1 === 2) {
          if (data.level === 3) {
            if (this[`${idsKey}`].length === 0 || this[`${idsKey}`].length > 0 && this[`${idsKey}`].indexOf(data.grandId) > -1) {
              if (data.parentId.indexOf(value) !== -1) {
                return true
              } else {
                return false
              }
            } else {
              return false
            }
          }
        }
        if (this[`${stFilter}`] && this[`${stFilter}`] * 1 === 3 && data.level === 2) {
          return false
        }
        if (this[`${idsKey}`].length === 0 && (data && data.text.indexOf(value) !== -1)) {
          flag = true
        } else if (this[`${idsKey}`].length > 0 && (this[`${idsKey}`].indexOf(data.parentId) > -1 || this[`${idsKey}`].indexOf(data.grandId) > -1) && data.text.indexOf(value) !== -1) {
          flag = true
        }
        return flag
      } else if (typeof value === 'object') {
        let flag = false
        for (let v of value) {
          if (v === ((data && data.text) || '') || this[`${idsKey}`].indexOf(data.parentId) > -1 || this[`${idsKey}`].indexOf(data.grandId) > -1) {
            flag = true
            this[`${idsKey}`].push(data.id)
          }
        }
        return flag
      }
    },
    clearFilter() {
      this.checkType = []
      this.filterText = ''
      this.filterIds = []
    }
  }
}
</script>
<style lang="scss" scoped>
.dialog-con{
  .left-tree,  .right-tree{
    // width: 49%;
    display: inline-block;
    vertical-align: top;
  }
}
.left-tree >>> .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color:  #428bca;
  color: #ffffff;
}
.buttons{
  width: 100%;
}
</style>
